package com.zhaolei.jpaswaggervue.controller;

import com.zhaolei.jpaswaggervue.pojo.Student;
import com.zhaolei.jpaswaggervue.service.StudentService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author 15579
 * 2019/6/3 14:28
 * 文件说明：Student控制层
 */
@RestController
@Api(value = "Swagger2 api 注释 Student控制层")
public class StuController {
    @Autowired
    private StudentService studentService;

    //根据条件分页查询
    @GetMapping("/findByPage")
    @ApiOperation(value = "分页查询",notes = "根据姓名模糊查询并分页")
    public Object findByPage(Integer pageNum, Integer pageSize, Student student){
        if(pageNum==null||pageNum<=0){
            pageNum=1;
        }
        Page<Student> page = studentService.findByPage(pageNum, pageSize,student);
       return  page;
    }

    //根据ID删除学生
    @DeleteMapping("/deleteStu")
    @ApiOperation(value = "删除",notes = "根据ID删除学生")
    public  int delteStu(@RequestParam("id") Integer id){
        System.out.println(id);
        try {
            studentService.deleteStu(id);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    //修改学生信息
    @PutMapping("/updateStu")
    @ApiOperation(value = "修改",notes = "修改学生信息")
    public  Object updateStu(@RequestBody Student student){
        Student updStudent = studentService.update(student);
        return  updStudent;
    }

    //新增学生信息
    @PostMapping("/addStu")
    @ApiOperation(value = "新增",notes = "新增学生信息")
    public Object addStu(@RequestBody Student student){
        System.out.println(student.getName());
        Student save = studentService.save(student);
        return  save;
    }


    //跳转至编辑页面
    @GetMapping("/gotoEdit")
    @ApiOperation(value = "跳转至编辑页面",notes = "根据编号判断是修改还是新增")
    public String gotoEdit(Integer id,Model model){
        if(id!=null){
            //根据ID查询学生信息并显示在页面
            Student student = studentService.findStudentById(id);
            model.addAttribute("stu",student);
        }
        return "edit";
    }
}
